import { getHost } from '@/utils/common/index.js'


export function useUploadFile() {
	const { host, imgHost } = getHost();
	const token = uni.getStorageSync('token');

	const afterRead = async (event) => {
		const fieldList = event.name;
		let files = event.file;
		if (!Array.isArray(files)) {
			files = [files];
		}

		files.map(item => {
			fieldList.push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})

		for (let i = files.length - 1; i >= 0; i--) {
			const current = fieldList[fieldList.length - i - 1];
			try {
				const path = await uploadFilePromise(current.url);
				current.status = 'success';
				current.message = '';
				current.url = imgHost + path;
				current.rawUrl = path;
			} catch (e) {
				current.status = 'failed';
				current.message = '上传失败';
			}
		}
	};

	const deleteFile = (event) => {
		const fieldList = event.name;
		const index = event.index;
		fieldList.splice(index, 1);
	}

	const uploadOversize = (maxSize, event) => {
		const currentFile = event.file[event.index];
		uni.showToast({
			title: `文件[${currentFile.name}]大小不能超过${maxSize}MB`,
			icon: "none"
		})
	}


	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: host + '/api/iuploadimg',
				filePath: url,
				name: 'pic',
				header: {
					Authorization: token
				},
				success: (res) => {
					if (res.statusCode === 200) {
						const data = JSON.parse(res.data)
						if (data.code === 0) {
							resolve(data.result)
						} else {
							reject(false)
						}
					} else {
						reject(false)
					}
				},
				fail() {
					reject(false)
				}
			})
		})
	};

	const checkUploadSuccess = (field) => {
		let success = true;
		for (let i = 0, length = field.length; i < length; i++) {
			const item = field[i];
			if (item.status !== "success") {
				success = false;
				break;
			}
		}
		return success;
	}

	return {
		afterRead,
		deleteFile,
		uploadOversize,
		checkUploadSuccess,
	};
}